// pages/weekly/Suggestion/Suggestion.js
const app = getApp()
Page({
	data: {
		blean: true,
		history: [],
		loading_status: true,
	},

	onLoad(e) {
		let that = this
		this.setData({
			history: app.$db.get('history') || []
		})
		this.getHot()
		console.log(this.data.history)
		this.executeWhenHistoryNotEmpty()
	},

	executeWhenHistoryNotEmpty() {
		let history = this.data.history;
		// 检查history数组是否不为空
		if (history && history.length > 0) {
			// 如果history不为空，执行ce方法
			console.log("已获取history，正在请求中")
			this.getToken_A()
		} else {
			// 如果history为空，你可以执行其他操作或者不做任何事情
			console.log('history数为空，不执行ce方法');
		}
	},
	// 热点获取
	getHot() {
		wx.cloud.callFunction({
			name: 'db',
			data: {
				$url: "getHot"
			}
		}).then(res => {
			let data = res.result.data
			let hot = data && data.map(item => item.hot_text)
			this.setData({
				hot: hot || []
			})
		})
	},

	// 接入文心一言
	getToken_A() {
		// 加载判断
		var ls = this.data.loading_status
		this.setData({
			loading_status: !ls
		})
		console.log("判断是" + ls)
		const url_token = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=Zr0exdXDxEOqWKm7m7tPucdj&client_secret=9sYsg6ORMAiuwx2q1OaEo37siFuqjvpO";
		wx.request({
			url: "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=Zr0exdXDxEOqWKm7m7tPucdj&client_secret=9sYsg6ORMAiuwx2q1OaEo37siFuqjvpO",
			method: "POST",
			header: {
				'Content-Type': 'application/json',
				'Accept': 'application/json'
			},
			success: res => {
				const access_token = res.data.access_token
				console.log("TOKEN:" + access_token)
				const url_chat = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token="+access_token
				const payload = {
					"messages": [{
						"role": "user",
						"content": "我这个星期丢弃了这些" + this.data.history + "请根据这些垃圾给予回收建议，简短回答"
					}]
				};
				wx.request({
					url: url_chat,
					method: "POST",
					data: payload,
					header: {
						'Content-Type': 'application/json'
					},
					success: (res) => {
						console.log(res.data, typeof (res.data));
						this.setData({
							result_A: res.data,
							loading_status: true
						})
					},
				});
			},
		});
	},
})